from rest_framework import serializers
from crouse import models

class Category(serializers.ModelSerializer):
    class Meta:
        model=models.CategoryModel
        fields=['cname','id']

class CateSerializer(serializers.ModelSerializer):
    child=Category(many=True)
    class Meta:
        model=models.CategoryModel
        fields='__all__'
class CourseSerializer(serializers.ModelSerializer):
    tea = serializers.SerializerMethodField(read_only=True)

    def get_tea(self, obj):
        return {'tname': obj.teacher.tname, 'job': obj.teacher.job,'tro': obj.teacher.intro,
                'headimg': 'http://127.0.0.1:8000' + str(obj.teacher.headimg)}
    class Meta:
        model=models.CourseModel
        fields="__all__"

# 课程列表
class CourseListSerializer(serializers.ModelSerializer):

    class Meta:
        model=models.CourseModel
        fields='__all__'

# 课程详情
class BannerImage(serializers.Serializer):
    file = serializers.ImageField()
    def validate(self, attrs):
        if attrs["file"].size>1024*1024*2:
            raise serializers.ValidationError("图片大小不得超过2M")
        return attrs

from drf_haystack.serializers import HaystackSerializer
from .search_indexes import CourseIndex

class CourseIndexSer(HaystackSerializer):
    class Meta:
        index_classes = [CourseIndex]
        fields = ['text', 'id', 'cname', 'intro','teacher','cover','price','discount','level','video','ishome','ishot']